<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use App\Facades\SmsCode;

class MobileVerify
{
    /**
     * 手机号&验证码 验证中间件
     * 用于验证手机号
     *
     * @param Request $request
     * @param Closure $next
     * @param string $mobileKey
     * @param string $codeKey
     *
     * @return mixed
     * @throws ValidationException
     */
    public function handle(Request $request, Closure $next, $mobileKey = 'mobile', $codeKey = 'sms_code')
    {
        $mobile = $request->input($mobileKey);
        $code = $request->input($codeKey);

        if (!$code) {
            throw ValidationException::withMessages([
                $codeKey => '验证码不能为空'
            ]);
        } elseif (!$mobile) {
            throw ValidationException::withMessages([
                $mobileKey => '手机号不能为空'
            ]);
        } elseif (!$check = SmsCode::check($mobile, $request->input($codeKey))) {
            throw ValidationException::withMessages([
                $codeKey => '验证码不正确'
            ]);
        }

        $response = $next($request);

        // 请求处理成功时清掉验证码发送记录
        if ($response->isSuccessful() || ($response->isRedirection() && is_null($response->exception))) {
            SmsCode::forget($mobile);
        }

        return $response;
    }

}
